<template>
  <a-row :gutter="10">
    <a-col :md="8" :sm="24">
      <div style="padding-left:16px; height: 100%; margin-top: 5px">
        <!-- 按钮操作区域 -->
        <a-row class="table-operator">
          <a-button @click="handleAdd(1)" type="primary">添加部门</a-button>
          <a-button @click="handleAdd(2)" type="primary">添加下级</a-button>
          <a-button title="删除多条数据" @click="handleDel" type="default">删除</a-button>
          <dept-form v-if="addVisible" ref="deptForm" @ok="loadTree"></dept-form>
        </a-row>
        <a-alert type="info" :showIcon="true">
          <div slot="message">
            当前选择：<span v-if="this.selectedKeys.length > 0">{{ this.selectedRows.name }}</span>
            <a v-if="this.selectedKeys.length > 0" style="margin-left: 10px" @click="onClearSelected">取消选择</a>
          </div>
        </a-alert>

        <a-input-search @search="onSearch" style="width:100%; margin-top: 10px" placeholder="请输入区域名称" />
        <!-- 树-->

        <!--组织机构-->
        <a-tree
            showLine
            :selectedKeys="selectedKeys"
            :checkStrictly="true"
            @select="onSelect"
            :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
            :treeData="departTree"
            :replace-fields="replaceFields"
            :autoExpandParent="autoExpandParent"
            :expandedKeys="expandedKeys"
            @expand="onExpand"
        />

      </div>
    </a-col>
    <a-col :md="16" :sm="24">

      <a-tabs defaultActiveKey="2" @change="callback">
        <a-tab-pane tab="基本信息" key="1" forceRender>
          <dept-form-card ref="deptFormCard" @ok="loadTree"></dept-form-card>
        </a-tab-pane>

        <a-tab-pane tab="用户信息" key="2">
          <user-form-card ref="userFormCard" @ok="loadTree"></user-form-card>
        </a-tab-pane>
      </a-tabs>

    </a-col>
  </a-row>
</template>

<script>
import { delDepart, queryDepartTreeList, searchByKeywords } from '@/api/api'
import deptFormCard from './model/dept-form-card'
import userFormCard from './model/user-form-card'
import deptForm from './model/dept-form'

export default {
  name: "dept",
  components: {
    deptForm,
    deptFormCard,
    userFormCard
  },
  data () {
    return {
      departTree: [],
      replaceFields: {
        children: 'children',
        title: 'name',
        key: 'id',
      },
      selectedRows: {},
      selectedKeys: [],
      expandedKeys: [],
      autoExpandParent: false,
      addVisible: false,
    }
  },
  created () {
    this.loadTree()
  },
  methods: {
    loadTree () {
      var that = this
      that.departTree = []
      queryDepartTreeList().then((res) => {
        if (res.success && res.result) {
          for (let i = 0; i < res.result.length; i++) {
            let temp = res.result[i]
            that.departTree.push(temp)
            that.setThisExpandedKeys(temp)
          }
        }
      })
    },
    onSearch (value) {
      let that = this
      if (value) {
        searchByKeywords({ name: value }).then((res) => {
          if (res.success) {
            that.departTree = []
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i]
              that.departTree.push(temp)
            }
          } else {
            that.$message.warning(res.message)
          }
        })
      } else {
        that.loadTree()
      }
    },
    setThisExpandedKeys (node) {
      //只展开一级目录
      if (node.children && node.children.length > 0) {
        this.expandedKeys.push(node.id)
        //下方代码放开注释则默认展开所有节点
        /**
         for (let a = 0; a < node.children.length; a++) {
            this.setThisExpandedKeys(node.children[a])
          }
         */
      }
    },
    onExpand (expandedKeys) {
      console.log('onExpand', expandedKeys);
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onSelect (selectedKeys, info) {
      if (info.selected) {
        this.selectedRows = info.selectedNodes[0].data.props
        console.log('onSelect', this.selectedRows);
        this.selectedKeys = selectedKeys;
        if (this.selectedRows.pid === '0') {
          this.selectedRows.pid = '一级部门'
        }
        // 赋值部门信息
        let deptRow = {
          id: this.selectedRows.id,
          pid: this.selectedRows.pid,
          name: this.selectedRows.name,
          sort: this.selectedRows.sort,
          createDate: this.selectedRows.createDate,
        }
        this.$refs.deptFormCard.dataForm = deptRow
        this.$refs.deptFormCard.departTree = [ ...[{ id: '0', pid: '0', name: '一级部门' }], ...this.departTree ]
        // 赋值部门用户
        this.$refs.userFormCard.queryParam.deptId = selectedKeys[0]
        this.$refs.userFormCard.searchQuery()
      }
    },
    handleAdd (flag) {
      if (flag === 2) {
        if (this.selectedKeys.length === 0) {
          return this.$message.warning('请选择一条记录!')
        }
      }
      this.addVisible = true
      this.$nextTick(() => {
        if (flag === 2) {
          let deptRow = {
            pid: this.selectedRows.id,
            name: '',
            sort: 0,
          }
          this.$refs.deptForm.dataForm = deptRow
        } else {
          this.$refs.deptForm.dataForm = this.$refs.deptForm.$options.data().dataForm
        }
        console.log('this.departTree', this.departTree)
        this.$refs.deptForm.departTree = [ ...[{ id: '0', pid: '0', name: '一级部门' }], ...this.departTree ]
        this.$refs.deptForm.init()
      })
    },
    handleDel () {
      if (this.selectedKeys.length === 0) {
        return this.$message.warning('请选择一条记录!')
      }
      delDepart(this.selectedKeys).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadTree()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    onClearSelected () {
      this.selectedRows = {}
      this.selectedKeys = []
      this.$refs.deptFormCard.dataForm = {}
    },
    callback (key) {
      //console.log(key)
    },
  }
}
</script>

<style scoped>

</style>
